﻿using DevExpress.Mvvm;
using HandyControl.Controls;
using HandyControl.Tools;
using PlaceOrder_Client.Models.Common;
using PlaceOrder_Client.ViewModels;
using PlaceOrder_Core.Helper;
using PlaceOrder_Shared.Models.Common;
using Prism.DryIoc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using ScrollViewer = System.Windows.Controls.ScrollViewer;

namespace PlaceOrder_Client.Views
{
    /// <summary>
    /// ChatWindow.xaml 的交互逻辑
    /// </summary>
    public partial class ChatWindow : System.Windows.Controls.UserControl
    {
        private ScrollViewer _scrollViewer;
        public ChatWindow()
        {
            InitializeComponent();

            //var viewModel = (ChatWindowViewModel)this.DataContext;
            //if(viewModel==null)
            //{
            //    return;
            //}
            //viewModel.ScrollToBottomRequested += (s, e) => ScrollToBottom();

            Loaded += async (s, e) =>
            {
                await Task.Delay(100); // 等待一段时间确保 DataContext 设置完毕
                var viewModel = (ChatWindowViewModel)this.DataContext;
                if (viewModel != null)
                {
                    viewModel.ScrollToBottomRequested += (sender, args) => ScrollToBottom();
                    viewModel.ScrollToBottom();

                }
            };

            Messenger.Default.Register<string>(this, MessageToken.ChatMessageBlink, Blink);

            
        }

        private void Blink(string title)
        {
            PrismApplication.Current.Dispatcher.InvokeAsync(()=>{
                if (title == ChatTitleTextBlock.Text)
                {
                    StartBlinking(title);
                }
            });
           
        }

        private void ScrollToBottom()
        {
            PrismApplication.Current.Dispatcher.Invoke(() =>
            {
                if (ListBoxChat.Items.Count > 0)
                {
                    var lastItem = ListBoxChat.Items[ListBoxChat.Items.Count - 1];
                    ListBoxChat.ScrollIntoView(lastItem);
                }
            });
        }
        Storyboard blinkingAnimation = new Storyboard();
        ColorAnimation colorAnimation = new ColorAnimation();

        private SolidColorBrush chatTitleBackgroundBrush;
        public void StartBlinking(string title)
        {
             blinkingAnimation = new Storyboard();

            var opacityAnimation = new DoubleAnimation
            {
                From = 1.0,
                To = 0.0,
                Duration = new Duration(TimeSpan.FromSeconds(0.6)),
                AutoReverse = true,
                RepeatBehavior = RepeatBehavior.Forever
            };

            Storyboard.SetTarget(opacityAnimation, ChatTitleTextBlock);
            Storyboard.SetTargetProperty(opacityAnimation, new PropertyPath("Opacity"));

            blinkingAnimation.Children.Add(opacityAnimation);

            if (title == "国利")
            {
                chatTitleBackgroundBrush = new SolidColorBrush(Colors.DarkBlue);
                ChatTitleBackgroundBrush.Color = Colors.DarkBlue;
                ChatTitleTextBlock.Background = chatTitleBackgroundBrush;
                colorAnimation = new ColorAnimation
                {
                    From = Colors.DarkBlue,
                    To = Colors.Red,
                    Duration = new Duration(TimeSpan.FromSeconds(0.8)),
                    AutoReverse = true,
                    RepeatBehavior = RepeatBehavior.Forever
                };

                var brush = new SolidColorBrush(Colors.Transparent);
                ChatTitleTextBlock.Background = brush;

                Storyboard.SetTarget(colorAnimation, chatTitleBackgroundBrush);
                Storyboard.SetTargetProperty(colorAnimation, new PropertyPath(SolidColorBrush.ColorProperty));
                blinkingAnimation.Children.Add(colorAnimation);
            }

            blinkingAnimation.Begin(this,true);
        }


        public void StopBlinking()
        {
            //var blinkingAnimation = (Storyboard)ChatTitleTextBlock.Resources["BlinkingAnimation"];
            if (blinkingAnimation != null)
            {
                blinkingAnimation.Stop(ChatTitleTextBlock);

                blinkingAnimation.Stop(this);
                ChatTitleTextBlock.Opacity = 1.0; // Ensure opacity is reset
                ChatTitleTextBlock.Background = new SolidColorBrush(Colors.Transparent); // Reset background color
            }
            //if (colorAnimation != null)
            //{
            //    colorAnimation.Stop(this);
            //}
        }

        private void ChatTitleTextBlock_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            StopBlinking();

            ChatTitleBackgroundBrush.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#426cee");
        }

        private void ChatTitleBorder_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            StopBlinking();

            ChatTitleBackgroundBrush.Color = (System.Windows.Media.Color)System.Windows.Media.ColorConverter.ConvertFromString("#426cee");
        }

        private bool blocking = false;
        private void ChatBubble_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {

            var chatBubble = (PlaceOrder_Client.Controls.ChatBubble)sender;
            if(chatBubble.Tag==null)
            {
                Growl.WarningGlobal("该消息记录没有MessageId");
                return;

            }
            string messageId = chatBubble.Tag.ToString();
            string chatMessage = chatBubble.Content.ToString();
            int brokerId = chatBubble.BrokerId;

            string brokerName = OrderListViewModel.ChatReceivers.Where(o => o.Brokerid == brokerId).FirstOrDefault()?.FormattedTarget;
            //Growl.InfoGlobal(chatBubble.Tag.ToString());
            // 获取 DataContext 并尝试将其转换为 ChatInfoModel
            long? tradeId = 0;
            if (chatBubble.DataContext is ChatInfoModel chatInfo)
            {
                 tradeId = chatInfo.TradeId;
                // 继续处理 tradeId
            }
            try
            {
                if (blocking)
                {
                    Growl.WarningGlobal("有正在执行的任务");
                    return;
                }
                blocking = true;
                var viewModel = new RequestChatMessageReviewViewModel(brokerId,brokerName,chatMessage,messageId,tradeId);
                var parentWindow = PrismApplication.Current.Windows.OfType<ChatMessageWindow>().FirstOrDefault();
                if(parentWindow==null)
                {
                    AppLog.WriteError($"双击申请复议聊天,{messageId},{chatMessage},没有ChatMessageWindow");
                    return;
                }
                //selectedUserTrade = new UserTrade(userTrade);
                // 创建新窗口并设置DataContext
                var window = new RequestChatMessageReviewView
                {
                    DataContext = viewModel,
                    Owner = parentWindow, // 设置父窗口
                    WindowStartupLocation = WindowStartupLocation.CenterOwner, // 设置窗口启动位置为父窗口中心
                };
                window.AddDefaultTradeNum("1111");
                viewModel.CloseWindowAction = window.Close;
                window.ShowDialog();

            }
            catch(Exception ex)
            {
                AppLog.WriteError($"双击申请复议聊天,{messageId},{chatMessage},异常{ex.Message}--{ex.StackTrace}");
            }
            finally
            {
                blocking = false;
            }
        }
    }
}
